import random
from datetime import datetime
from .operations import Addition, Subtraction

class Exercise:
    """练习类，用于生成一套习题"""
    def __init__(self, exercise_id, question_count=50):
        self.exercise_id = exercise_id
        self.question_count = question_count
        self.questions = []
        self.create_time = datetime.now()
        self.used_questions = set()
    
    def generate_questions(self):
        """生成习题"""
        # 清空已有题目
        self.questions.clear()
        self.used_questions.clear()
        
        # 生成加法题
        for _ in range(self.question_count // 2):
            while True:
                operation = Addition.generate_random()
                question_str = str(operation)
                if question_str not in self.used_questions:
                    self.used_questions.add(question_str)
                    self.questions.append({
                        'operation': operation,
                        'question': question_str,
                        'answer': str(operation.get_result())
                    })
                    break
        
        # 生成减法题
        for _ in range(self.question_count // 2):
            while True:
                operation = Subtraction.generate_random()
                question_str = str(operation)
                if question_str not in self.used_questions:
                    self.used_questions.add(question_str)
                    self.questions.append({
                        'operation': operation,
                        'question': question_str,
                        'answer': str(operation.get_result())
                    })
                    break
        
        # 如果题目数是奇数，随机添加一道题
        if self.question_count % 2 == 1:
            operation_class = random.choice([Addition, Subtraction])
            while True:
                operation = operation_class.generate_random()
                question_str = str(operation)
                if question_str not in self.used_questions:
                    self.used_questions.add(question_str)
                    self.questions.append({
                        'operation': operation,
                        'question': question_str,
                        'answer': str(operation.get_result())
                    })
                    break
        
        # 打乱题目顺序
        random.shuffle(self.questions)
    
    def to_dict(self):
        """转换为字典格式以便保存"""
        return {
            'exercise_id': self.exercise_id,
            'questions': [{
                'question': q['question'],
                'answer': q['answer']
            } for q in self.questions],
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S')
        }
    
    def format_questions(self):
        """格式化显示习题"""
        formatted = "\n习题内容：\n" + "="*80 + "\n"
        
        # 每4个算式一行
        for i in range(0, len(self.questions), 4):
            line_questions = self.questions[i:i+4]
            # 算式部分
            question_line = ""
            # 答案部分
            answer_line = ""
            
            for j, q in enumerate(line_questions):
                # 保持每个算式占20个字符的宽度
                question = f"{i+j+1}. {q['question']}"
                answer = f"{i+j+1}. {q['question']}{q['answer']}"
                question_line += f"{question:<20}"
                answer_line += f"{answer:<20}"
            
            formatted += question_line + "\n"
            formatted += answer_line + "\n"
            formatted += "-"*80 + "\n"
        
        return formatted 